package com.zeratul.cloud.demo1.controller;

import com.zeratul.cloud.demo2.api.RemoteUserApi;
import com.zeratul.cloud.demo2.api.domain.bo.UserQueryBo;
import com.zeratul.cloud.demo2.api.domain.vo.UserVo;
import com.zeratul.common.core.result.R;
import com.zeratul.common.satoken.utils.LoginHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.rpc.RpcContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.CompletableFuture;

/**
 * 测试远程调用的Controller
 */
@RestController
@RequestMapping("/api/remote")
@Slf4j
public class RemoteController {

    @DubboReference(async = true)
    private RemoteUserApi remoteUserApi;

    @Autowired
    private RemoteUserApi remoteUserApi2;

    @GetMapping("/test")
    public R remoteTest(Integer id){
        log.info("【调用方】调用方触发！参数：{}", id);
        log.info("【调用方】登录用户：{}", LoginHelper.getLoginUser());
        //远程调用
        UserVo userVo = null;
        if (id == 1) {
            userVo = remoteUserApi.getById(new UserQueryBo().setId(id));

            // 拿到调用的Future引用，当结果返回后，会被通知和设置到此Future
            CompletableFuture<UserVo> helloFuture = RpcContext.getServiceContext().getCompletableFuture();
            //同步获得返回值
//            try {
//                userVo = helloFuture.get();
//            } catch (Exception e) {
//                throw new RuntimeException(e);
//            }
            // 异步获得返回值
            helloFuture.whenComplete((retValue, exception) -> {
                if (exception == null) {
                   log.debug("【调用方】异步回调获得结果：{}", retValue);
                } else {
                    exception.printStackTrace();
                }
            });

        } else if (id == 2) {
            userVo = remoteUserApi2.getById(new UserQueryBo().setId(id));
        }
        log.info("【调用方】远程调用成功，返回结果：{}", userVo);
        return R.success(userVo);
    }
}
